<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="../../plugins/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/rmp.css" media="all">
    <style>
    	.layui-form-pane .layui-form-label {
			    width: 320px;
			    text-align: left;
			}
		.layui-form-pane .layui-input-block {
			    margin-left: 320px;
			}
    </style>
</head>
<body>
<div class="layui-fluid">
    <blockquote class="layui-elem-quote" style="margin-top: 16px;">
        <button class="layui-btn">需求标识和备注设定</button>
        <button class="layui-btn">选择分析数据</button>
        <button class="layui-btn layui-btn-danger">设置默认数值</button>       
        <span class="rmp-serverInfo-btn-tools-right">
            <button class="layui-btn">历史记录</button>
        </span>
    </blockquote>
    <div class="rmp-monitoring-content">
       <div>
       		<fieldset class="layui-elem-field" id="server-list" style="height:240px;">

			</fieldset>	
       </div>
       <br>
       <div class="layui-row layui-col-space20">
       		<div class="layui-col-md4">
		    <fieldset class="layui-elem-field" id="applicationResources" style="height:350px;padding:10px;">
				<legend>应用主机资源数据</legend>
			</fieldset>	
		  	</div>
		  	<div class="layui-col-md4">
		    <fieldset class="layui-elem-field" id="databaseResources" style="height:350px;padding:10px;">
				<legend>数据库资源数据</legend>

			</fieldset>	
		  	</div>
		  	<div class="layui-row layui-col-md4">
			    <fieldset class="layui-elem-field" id="clusterResources" style="height:350px;padding:10px;">
					<legend>集群资源数据</legend>
	
				</fieldset>	
		  	</div>
       </div>
       <div class="layui-row">
           <button class="layui-btn" id="data-analyze">生成最终JSON数据</button>
           <button class="layui-btn layui-btn-primary" id="data-reset">清空已选择</button>
       </div>
    </div>
</div>
<script type="text/html" id="apiDataHistoryBar">
  <a class="layui-btn layui-btn-sm" lay-event="send-api-data">发送数据</a>
  <a class="layui-btn layui-btn-sm layui-btn-danger" lay-event="del-api-data">删除</a>
</script>
<script type="text/html" id="apiDataExcelTpl">
  <a class="layui-table-link" href="../../{{ d.filePath }}" target="_blank">{{ d.filePath }}</a>
</script>
<script src="../../plugins/jquery.js"></script>
<script src="../../plugins/layui/layui.js"></script>
<script src="../../plugins/Sortable/Sortable.js"></script>
<script src="../../js/global.js"></script>
<script>
	var globalLoadIndex;
	var currentIndex;
	//当前历史记录文件ID
	var fileId;
	//默认数值
	var apiData = getLocalData("defaultApiData", true);
	//属于每个服务器主机的默认数值
	var serverApiData = {};
	
	var countNum = 0;
	//需求信息
	var apiIdentity = "";
	var apiName = "";
	var mark = "";
	
	//分析数据结果对象
	var analyzeDataObject = {};
	
    layui.use(['layer', 'form', 'table', 'laydate'], function() {
        var layer = layui.layer,
        	form = layui.form,
        	table = layui.table,
        	laydate = layui.laydate;      
        
        if (apiData == null) {
			//获取默认的值
			$.getJSON('../../js/apiData.json', function(json){
				apiData = json;
				saveLocalData("defaultApiData", apiData);
			});
		}
        
        //初始化下方资源池
        var resourcesPoolInfo = {
        	applicationResources:'layui-btn-normal',
        	databaseResources:'layui-btn',
        	clusterResources:'layui-btn-danger'
        };        
        $.each(resourcesPoolInfo, function(i, n){
        	Sortable.create(document.getElementById(i)
    				, {group: {name:"server", pull:false}, sort:false, onAdd:function (evt) {
    		        	$(evt.item).removeClass('layui-btn-primary').addClass(n);
    		        	$(evt.item).attr("count-id", countNum++);
    		        	serverApiData[$(evt.item).attr("count-id")] = {};
    		        	serverApiData[$(evt.item).attr("count-id")][i] = $.extend(true, {}, analyzeDataObject[$(evt.item).attr('view-id')][i]);
    		    	}});
        });
        
        $(document).delegates({       	
        	//历史对接记录
        	".rmp-serverInfo-btn-tools-right > button":function(){
        		loading(true, '正在查询中');
        		$.post(REPORT_HISTORY_LIST_API_DATA_HISTORY_URL, {userKey:userKey}, function(json){
        			loading(false);
        			validatReturnJson(json, function(){
						layer_show('历史数据', templates['rmp-dataapi-api-data-history'].render(json.data), 1065, 600, 1, function(layero, index){
							table.init('api-data-history', {
								initSort: {
								    field: 'saveTime' //排序字段，对应 cols 设定的各字段名
								    ,type: 'desc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
								  }
							}); 
                		});
        			});
        		});       		
        	},
        	//设定对接地址和需求标识
        	"blockquote > button:eq(0)":function(){    		
        		layer_show('设置需求标识和备注', templates['rmp-dataapi-setting-api-url'].render({mark:mark,apiName:apiName,apiIdentity:apiIdentity || ''}),
        				680, 340, 1);
        	},
        	//设定默认值
        	"blockquote > button:eq(2)":function(){       		
        		layer_show('默认数值设定', templates['rmp-dataapi-setting-default-data'].render(apiData), 600, 640, 1, function(layero, index){
        			$(layero).find('#del-choose-server-data').remove();
        			$(layero).find('#rmp-apidata-setting-api-data-btns > button:eq(0)').click();
				});     		
        	},
        	//设定历史文件id
        	"blockquote > button:eq(1)":function() {
        		currentIndex = layer_show('设定历史记录文件ID', templates['rmp-dataapi-setting-file-tpl'], 700, 240, 1);
        		
        	},
        	//不同类型服务器信息展示
        	'#rmp-monitoring-column-view-btns > button':function(){
                var serverType = $(this).attr('server-type');
                $(this).parents('.layui-field-box').find('.choose-server').hide();
                $(this).parents('.layui-field-box').find('.choose-server[server-type="' + serverType + '"]').show();
                $(this).removeClass('layui-btn-primary').siblings('button').addClass('layui-btn-primary');
            },
            //默认数值设定
            '#rmp-apidata-setting-api-data-btns > button':function(){
            	var resourceType = $(this).attr('resource-type');
                $(this).parents('.layer-show-view').find('.layui-form-item[resource-type]').hide();
                $(this).parents('.layer-show-view').find('.layui-form-item[resource-type="' + resourceType + '"]').show();
                $(this).removeClass('layui-btn-primary').siblings('button').addClass('layui-btn-primary');
            },
            
            'fieldset > button':{
            	//设置该项的默认值
            	'click':function(){
            		var resourceType = $(this).parent('fieldset').attr('id');
            		var countId = $(this).attr('count-id');
            		var thisApiData = serverApiData[countId + ""];
            		if (thisApiData == null) {
            			thisApiData = $.extend(true, {}, apiData[resourceType]);
            			serverApiData[countId + ""] = {
            					defaultData:thisApiData
            			};
            		}
            		window.plele = $(this);
            		globalLoadIndex = layer_show('默认数值设定', templates['rmp-dataapi-setting-default-data'].render(serverApiData[countId + ""]), 600, 640, 1, function(layero, index){
    					$(layero).find('#rmp-apidata-setting-api-data-btns').remove();
    					$(layero).find('#update-default-api-data-flag').val("1");
    					$(layero).find('.layui-form-item[resource-type]').show();
    					$(layero).find('#count-id').val(countId);   					
    				});
            		
            	}
            },
            '#del-choose-server-data':function(){
            	var that = this;
            	layer.confirm('确认删除此项？', function(index){
            		delete serverApiData[$(that).siblings('#count-id').val()];
            		window.plele.remove();             		
            		layer.close(globalLoadIndex);
            		layer.msg('删除成功!', {icon:1, time:1200});
            		layer.close(index);
            	});
            },
            //清空所有已选择
            '#data-reset':function(){
            	layer.confirm('确认清空所有已选择?', function(index){
            		$('fieldset > button').remove();
            		serverApiData = {};
            		layer.msg('已清空!', {icon:1, time:1200});
            		layer.close(index);
            	})
            },
            //重置选择的文件和时间
            '#reset-file-time':function(){
            	var $form = $(this).parents('form');
            	if ($form.find('input[name="time"]').val() == '') {
            		return;
            	}           	
        		$('button[lay-filter="setting-file-time"]').text('查询历史记录');       		
        		$form.find('input[name="fileId"]').val('');
        		$form.find('input[name="time"]').val('');
        		$form.find('.layui-form-item:eq(1)').addClass('layui-hide');
        		layer.msg('已重置,请重新选择!', {time:1500});
        	},
            //获取最终json数据
            '#data-analyze':function(){
            	var sendData = {
            			userKey:userKey,
            			serverList:{
            				applicationResources:[],
            				databaseResources:[],
            				clusterResources:[]
            			}
            	};
            	
            	//获取所有已选择数据
            	$('fieldset > button').each(function(i, ele){
            		var resourceType = $(this).parent('fieldset').attr('id');
            		sendData.serverList[resourceType].push({
            			viewId:$(this).attr('view-id'),
            			serverType:$(this).attr('server-type'),
            			apiData:serverApiData[$(this).attr('count-id')] == null ? null : serverApiData[$(this).attr('count-id')][resourceType]
            		});
            		
            	});
            	
            	if ((sendData.serverList.applicationResources.length + sendData.serverList.databaseResources.length 
            			+ sendData.serverList.clusterResources.length) == 0) {
            		layer.msg('请选择至少一项资源数据!', {time:1500});
            		return;
            	}

            	sendData.serverList = JSON.stringify(sendData.serverList);
            	loading(true, '正在努力分析数据中...');
            	$.post(REPORT_HISTORY_CREATE_FINAL_API_DATA_JSON_URL, sendData, function(json){
            		loading(false);
            		validatReturnJson(json, function(){
            			layer.prompt({
                			  formType: 2,
                			  value: JSON.stringify(json.data, null, 4),
                			  title: '编辑完整分析数据',
                			  area: ['600px', '520px'],
                			  maxlength:9999999,
                			  btn: ['确认保存数据', '取消'],
                			  shade:0
                			}, function(value, index, elem){
                				if (apiIdentity.length == 0) {
                					layer.msg('需求标识设置不完整!',{time:1500} );
                					return false;
                				}
                				var sendData = {
                					apiName:apiName,
                					mark:mark,
                					userKey:userKey,
                					apiIdentity:apiIdentity,
                					apiData:JSON.stringify(json.data),
                					apiMark:getLocalData("defaultApiData", false)
                				};
                				$.post(REPORT_HISTORY_SAVE_API_DATA_URL, sendData, function(jd){
                					validatReturnJson(jd, function(){
                						layer.alert('<span style="color:red;">保存信息成功,请点击右上角历史记录查询</span>', {icon:1});
                					});
                				});
                			});                			
            		});
            	});
            }
        });
        
        form.on('submit(update-api-url)', function(data){
        	apiIdentity = data.field.apiIdentity;
        	apiName = data.field.apiName;
        	mark = data.field.mark;
        	layer.msg('更新成功!', {icon:1, time:1500});
        	return false;
        });        
        
        form.on('submit(update-default-api-data)', function(data){
        	var $form = $(data.form);
        	var countId = $form.find('#count-id').val();
        	var flag = $form.find('#update-default-api-data-flag').val();
        	
        	var thatApiData = apiData;
        	if (flag == '1') {
        		thatApiData = serverApiData[countId + ""];
        	}
        	
        	$.each(thatApiData, function(type, item){
        		$.each(item, function(name, info) {
        			thatApiData[type][name]['value'] = $form
        				.find('.layui-form-item[resource-type="' + type + '"] input[name="' + name + '"]').val();
        		})
        	});
        	if (flag != '1') {
        		apiData = thatApiData;
        		saveLocalData("defaultApiData", apiData);
        	}       	
        	layer.msg('更新成功!', {icon:1, time:1500});
        	return false;
        });
        
        
        form.on('submit(setting-file-time)', function(data){
        	var $form = $(data.form);
        	if (data.field.time == '') {  //验证文件是否存在并获取时间范围
        		loading(true);
  			  	$.post(REPORT_HISTORY_API_DATA_VALIDATE_FILE_INFO_URL, {userKey:userKey, fileId:data.field.fileId}, function(json){
  			  		loading(false);
					validatReturnJson(json, function(){
						$form.find('button').text("确认选择");
						$form.find('input[name="time"]').parents('.layui-form-item').removeClass('layui-hide');
						laydate.render({
			                elem: $form.find('input[name="time"]')[0],
			                type:'datetime',
			                range:'~',
			                min: json.data.min,
			                max: json.data.max,
			                value:json.data.min + ' ~ ' + json.data.max
			            });
					});
  			  	});
        	} else { //获取分析结果数据
        		var sendData = {
        			userKey:userKey,
        			testTime:data.field.time,
        			fileId:data.field.fileId,
        			itemNames:{},
        			apiData:JSON.stringify(apiData)
        		};       	
        		loading(true, '正在努力分析数据中...')
        		$.each(serverInfos.serverTypes, function(serverType, n){
            		sendData.itemNames[serverType] = [];
            		$.each(serverInfos[serverType]["propertyObject"], function(itemName1, mark1) {
            			$.each(mark1, function(itemName2, mark2) {
            				sendData.itemNames[serverType].push(itemName1 + "." + itemName2);								
            			});
                	});
            	});
            	
            	sendData.itemNames = JSON.stringify(sendData.itemNames);
            	
            	$.post(REPORT_HISTORY_ANALYZE_API_DATA_URL, sendData, function(json) {
            		loading(false);
            		validatReturnJson(json, function(){
            			var templateData = {serverList:JSON.parse(json.data.serverList), analyzeDataObject:analyzeDataObject};
            			templates['rmp-dataapi-choose-server-panel'].render(templateData, function(string){
    						$("#server-list").html(string);
    						Sortable.create(document.getElementById('server-li')
    								, {group: {name:"server", pull:'clone', put:false}, sort:false});
    						$('#rmp-monitoring-column-view-btns > button:eq(0)').click();
    					});          			
            		});
            		layer.close(currentIndex);
            	});       		
        	}
        	return false;
        });
        
      //监听工具条
        table.on('tool(api-data-history)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
          var data = obj.data; //获得当前行数据
          var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）      
          if(layEvent === 'send-api-data'){ 
        	 layer.confirm('确认发送此条数据到对端接口吗？', {title:'提示'}, function(index){
        		loading(true, "正在发送数据到对端接口...");
              	$.post(REPORT_HISTORY_SEND_API_DATA_URL, {userKey:userKey,apiData:data.apiData, apiIdentity:data.apiIdentity, apiMark:getLocalData("defaultApiData", false)}, function(json){
              		loading(false);
              		validatReturnJson(json, function(){
              			layer.alert(json.msg);
              		}); 
              	});
        		layer.close(index);
        	  });        	  
          } else if(layEvent === 'del-api-data') {
        	  layer.confirm('确认删除此条数据(确保你已经将此条数据同步给对端接口了)？', {title:'警告'}, function(index){
        		  loading(true, "正在删除...");
            	  $.post(REPORT_HISTORY_DEL_API_DATA_URL, {userKey:userKey,id:data.id}, function(json){
              			loading(false);
              			validatReturnJson(json, function(){
              				obj.del();
              				layer.msg('删除成功!', {icon:1, time:1500});
              			}); 
              	  });       		  
        		  layer.close(index);
        	  });       	   
          }          
        });
    });
</script>
</body>
</html>